//
//  MyInfomationViewController.swift
//  WangPu
//
//  Created by xiaozhi on 15/10/22.
//  Copyright © 2015年 zhixiao. All rights reserved.
//

import UIKit

class MyInfomationViewController: BaseViewController {
    var cartTable:UITableView!
    var dataArray:[[String]]!
    var imageArray:[[String]]!
    var commitBtn:UIButton!
    var logoutSuccess:(()->Void)?
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = "我的资料"
        let backItem = UIBarButtonItem(image: UIImage(named: "back_icon"), style:UIBarButtonItemStyle.Plain, target:self, action:"goBack")
        backItem.tintColor = UIColor.whiteColor()
        self.navigationItem.leftBarButtonItem = backItem
        self.automaticallyAdjustsScrollViewInsets = false
        view.backgroundColor = commonBackgoundColor
        cartTable = UITableView(frame: CGRectMake(0, 64, view.bounds.size.width, 220), style: UITableViewStyle.Grouped)
        cartTable.backgroundColor = UIColor.clearColor()
        cartTable.separatorStyle = UITableViewCellSeparatorStyle.None
        cartTable.showsHorizontalScrollIndicator = false
        cartTable.showsVerticalScrollIndicator = false
        cartTable.dataSource = self
        cartTable.rowHeight = 60.0
        cartTable.delegate = self
        cartTable.scrollEnabled = false
        cartTable.registerClass(UITableViewCell.self, forCellReuseIdentifier: "payId")
        dataArray = [["实名认证"],["地址管理"],["我的收藏"]]
        imageArray = [["real_name"],["address"],["nor-collection_star"]]
        view.addSubview(cartTable)
        commitBtn = UIButton(frame: CGRectMake(25,CGRectGetMaxY(cartTable.frame)+30, view.bounds.size.width - 50, 40))
        commitBtn.setTitleColor(UIColor.whiteColor(), forState: UIControlState.Normal)
        commitBtn.setTitle("退出登录", forState: UIControlState.Normal)
        commitBtn.backgroundColor = commonRedColor
        commitBtn.addTarget(self, action: "logout", forControlEvents: UIControlEvents.TouchUpInside)
        commitBtn.layer.cornerRadius = 4.0
        commitBtn.titleLabel?.font = UIFont.systemFontOfSize(15)
        view.addSubview(commitBtn)
        // Do any additional setup after loading the view.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    func logout(){
        let request = NetWorkHelper()
        let parameters = NSMutableDictionary()
        parameters.setObject(GlobalDataHelper.instance.session!, forKey: "sessionid")
        request.requestStart("/account/logout", parameters: parameters,compeleteHandle:{ (data, response, error)  in
            dispatch_async(dispatch_get_main_queue()){
                self.hiddenProcessView()
            }
            if error == nil{
                var dic:NSDictionary?
                do {
                    dic = try NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions.AllowFragments) as? NSDictionary
                } catch let error as NSError {
                    print(error)
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("服务器数据异常")
                    }
                    return
                }
                if (dic?["result"])! as! String == "0"{
                    dispatch_async(dispatch_get_main_queue()){
                        self.showTips("注销成功"){
                            self.logoutSuccess?()
                            //                                self.loginSuccess?(userInfo: dic?["data"] as? NSDictionary)
                            self.navigationController?.popViewControllerAnimated(true)
                        }
                    }
                }
            }
        })
        self.showProcess("正在处理...")
    }
    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        navigationController?.navigationBarHidden = false
    }
    func  goBack(){
        self.navigationController?.popViewControllerAnimated(true)
    }
    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
extension MyInfomationViewController:UITableViewDataSource,UITableViewDelegate{
    func numberOfSectionsInTableView(tableView: UITableView) -> Int{
        return imageArray.count
    }
    func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return 1
    }
    func tableView(tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat{
        return 10
    }
    func tableView(tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat{
        return 1
    }
    func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) ->UITableViewCell{
        let cell = tableView.dequeueReusableCellWithIdentifier("payId", forIndexPath: indexPath)
        cell.textLabel?.frame = cell.contentView.bounds
        cell.textLabel?.textAlignment = NSTextAlignment.Left

        cell.textLabel?.text = dataArray[indexPath.section][indexPath.row]
        cell.textLabel?.font = UIFont.systemFontOfSize(14)
        cell.imageView?.image = UIImage(named: imageArray[indexPath.section][indexPath.row])
        cell.textLabel?.numberOfLines = 0
        cell.selectionStyle = UITableViewCellSelectionStyle.None
        cell.accessoryType = UITableViewCellAccessoryType.DisclosureIndicator
        if indexPath.section == 0{
            if let info = GlobalDataHelper.instance.is_authentication{
                if info == "0"{
                    let l = UILabel(frame: CGRectMake(0, 0, 50, 20))
                    l.text = "已认证"
                    l.font = UIFont.systemFontOfSize(14)
                    cell.accessoryView = l;
                    cell.accessoryType = UITableViewCellAccessoryType.None
                }
            }
        }
        return cell;
    }
    func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat{
        return 40
    }
    func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath){
        if indexPath.section == 0{
            if let info = GlobalDataHelper.instance.is_authentication{
                if info == "0"{
                    return
                }
                else{
                    let ctl = IdentifyViewController()
                    ctl.IdentifySuccess = {
                        self.cartTable.reloadData()
                    }
                    self.navigationController?.pushViewController(ctl, animated: true)
                }
            }

        }
        else  if indexPath.section == 1{
            let ctl = AddressManagerViewController()
            self.navigationController?.pushViewController(ctl, animated: true)
        }
        else{
            let ctl = MyCollectionViewController()
            self.navigationController?.pushViewController(ctl, animated: true)
        }
    }
}